<?php
/**
 * @package PWE.modele
 * @author Gmax <gmaxfr78@gmail.com>
 */
class modele_adresse extends modele {
    protected static $_table = 'adresse';
         
    private $_id = 0;
    private $_adresse1='';
    private $_adresse2='';
    private $_ville_id=0;
    private $_ville='';
    private $_cp='';
    private $_pays = 'france';
    private $_region_id=0;
    private $_region_nom='';
    private $_lat = '0';
    private $_lng = '0';
    private $_url_google = '';
    
    function __construct($id=null){
        if($id!==null){
            $this->_id = $id;
            $this->_constructObject();
        }else{
            $this->_id = 0;
        }
    }
    private function _constructObject(){
        $sqlQuery = 'SELECT ';
        $sqlQuery .= 't.*, ';
        $sqlQuery .= 'r.nom AS region_nom, ';
        $sqlQuery .= 'v.nom AS ville, ';
        $sqlQuery .= 'v.lat AS ville_lat, ';
        $sqlQuery .= 'v.lng AS ville_lng, ';
        $sqlQuery .= 'v.cp AS cp, ';
        $sqlQuery .= 'r.id AS region_id, ';
        $sqlQuery .= 'v.pays AS pays ';
        $sqlQuery .= 'FROM '.self::getTable().' as t ';
        $sqlQuery .= 'LEFT JOIN '.PWE::getPrefixBdd().'ville AS v ON v.id=t.ville_id ';
        $sqlQuery .= 'LEFT JOIN '.modele_region::getTable().' AS r ON r.id=v.region_id ';
        $sqlQuery .= 'WHERE t.id='.$this->_id.' ';
        $sqlQuery .= 'LIMIT 1';
        
        $datas = $this->_getOneResult($sqlQuery);
        if($datas){
            $this->_id = $datas['id'];
            $this->_adresse1 =  $datas['adresse1'];
            $this->_adresse2 =  $datas['adresse2'];
            $this->_ville_id =  $datas['ville_id'];
            $this->_ville =  $datas['ville'];
            $this->_cp = $datas['cp'];
            $this->_region_id = $datas['region_id'];
            $this->_region_nom = $datas['region_nom'];
            $this->_pays = $datas['pays'];
            if($datas['lat']!='0'&&$datas['lat']!=''&&$datas['lng']!='0'&&$datas['lng']!=''){
                $this->_lat = $datas['lat'];
                $this->_lng = $datas['lng'];
            }else{
                $this->_lat = $datas['ville_lat'];
                $this->_lng = $datas['ville_lng'];
            }
                        
            $this->_url_google = $datas['url_google'];
        }else{
            $this->_id = 0;
        }
    }
    public function getId(){
        return $this->_id;
    }
    public function getVilleId(){
        return $this->_ville_id;
    }
    public function getLng(){
        return $this->_lng;
    }
    public function getLat(){
        return $this->_lat;
    }
    public function getLatLng(){
        return $this->_lat.','.$this->_lng;
    }
    public function getUrlGoogle(){
        return $this->_url_google;
    }
    /**
     * retourne l'url gmap des coordonnées lat-lng
     * @return string
     */
    public function generateUrlGoogle(){
        if($this->getLat()==0&&$this->getLng()==0){
            $this->generateLatLng(true,true);
        }
        if($this->getLat()>0&&$this->getLng()>0){
            $url = 'http://maps.google.fr/maps?f=q&hl=fr&q='.$this->getLat().','.$this->getLng().'';
        }else{
            $adresse = '';
            $adresse .= $this->getAdresse1();
            if($this->getAdresse2()!=='')$adresse .= ' '.$this->getAdresse2();
            if($adresse!=='')$adresse .= ', ';
            $adresse .= $this->getCp().' '.$this->getVille().', '.$this->getPays();
            
            $url = 'http://maps.google.fr/maps?f=q&hl=fr&q='.$adresse;
        }
        
        return $url;
    }
    /**
     * retourne l'url gmap static de l'adresse
     * @param array $size array($width,$height)
     * @param int $zoom
     * @return string
     */
    public function generateUrlGoogleStatic($size=array(200,200),$zoom=14){
        $adresse2 = ($this->getAdresse2()!='')?','.$this->getAdresse2():'';
        $adresse = urlencode($this->getAdresse1()).$adresse2.','.$this->getCp().','.urlencode($this->getVille());
        $url = 'http://maps.googleapis.com/maps/api/staticmap?center='.$adresse.'&markers='.$adresse.'&zoom='.$zoom.'&size='.$size[0].'x'.$size[1].'&sensor=false';
        return $url;
    }
    /**
     * 
     * @param boolean $complete coordonnées précise de l'adresse
     * @param boolean $save enregistre les coordonnées en base de données
     */
    public function generateLatLng($complete=false,$save=false){
        $adresse = '';
        if($complete){
            $adresse .= $this->getAdresse1();
            if($this->getAdresse2()!=='')$adresse .= ' '.$this->getAdresse2();
            if($adresse!==''){
                $adresse .= ', ';
            }
        }
        $adresse .= $this->getCp().' '.$this->getVille().', '.$this->getPays();
        
        $base_url="http://maps.googleapis.com/maps/api/geocode/xml?";
        $request_url = $base_url . "address=" . urlencode($adresse).'&sensor=false';
        
        $xml = simplexml_load_file($request_url) or die("url not loading");
        
        $coords['lat']=$coords['lon']='';
        $coords['status'] = $xml->status ;
        if($coords['status']=='OK'){
            $this->_lat = $xml->result->geometry->location->lat;
            $this->_lng = $xml->result->geometry->location->lng;
        }
        if($save){
            if(!$complete&&$this->getVilleId()>0){
                $sqlQuery = 'UPDATE '.PWE::getPrefixBdd().'ville SET ';
                $sqlQuery .= 'lat="'.$this->getLat().'", ';
                $sqlQuery .= 'lng="'.$this->getLng().'" ';
                $sqlQuery .= 'WHERE id='.$this->getVilleId().' LIMIT 1';
                bdd_sql::doSql($sqlQuery,false);
            }elseif($this->getId()>0){
                $sqlQuery = 'UPDATE '.self::getTable().' SET ';
                $sqlQuery .= 'lat="'.$this->getLat().'", ';
                $sqlQuery .= 'lng="'.$this->getLng().'" ';
                $sqlQuery .= 'WHERE id='.$this->getId().' LIMIT 1';
                bdd_sql::doSql($sqlQuery,false);
            }
        }
    }
    public function getCp(){
        return $this->_cp;
    }
    public function getNumDepartement(){
        return substr($this->getCp(),0,2);
    }
    public function getRegionId(){
        return $this->_region_id;
    }
    public function getRegionNom($input=false){
        if($input)return $this->inputFormat(strtolower($this->_region_nom));
        else return ucwords($this->outputFormat($this->_region_nom));
    }
    /**
     * renvoi le nom de la ville
     * @param boolean $input
     * @return string
     */
    public function getVille($input=false){
        if($input)return $this->inputFormat(strtolower($this->_ville));
        else return ucwords($this->outputFormat($this->_ville));
    }
    public function getPays($input=false){
        if($input)return $this->inputFormat(strtolower($this->_pays));
        else return ucwords($this->outputFormat($this->_pays));
    }
    public function getAdresse1($input=false){
        if($input)return $this->inputFormat($this->_adresse1);
        else return $this->outputFormat($this->_adresse1);
    }
    public function getAdresse2($input=false){
        if($input)return $this->inputFormat($this->_adresse2);
        else return $this->outputFormat($this->_adresse2);
    }
    public function getDatas($input=false){
        $data = array();
        $data['id'] = $this->getId();
        $data['ville_id'] = $this->getVilleId();
        $data['ville'] = $this->getVille($input);
        $data['adresse1'] = $this->getAdresse1($input);
        $data['adresse2'] = $this->getAdresse2($input);
        $data['region'] = $this->getRegionNom($input);
        $data['region_id'] = $this->getRegionId();
        $data['cp'] = $this->getCp();
        $data['lat_lng'] = $this->getLatLng();
        $data['lat'] = $this->getLat();
        $data['lng'] = $this->getLng();
        $data['url_google'] = $this->getUrlGoogle();
        $data['pays'] = $this->getPays($input);
        return $data;
    }
    public function setDatas($datas) {
        foreach($datas as $k=>$v){
            if(substr($k, 0, 1) !== '_') $k = '_'.$k;
            if($k != '_id' && property_exists(get_class($this),$k)){
                $this->$k = $v;
            }
        }
        return true;
    }
    private function _checkVille($nom,$cp,$pays='france'){
        $sqlCheckVille = 'SELECT * FROM '.PWE::getPrefixBdd().'ville WHERE nom="'.$nom.'" AND cp="'.$cp.'" AND pays="'.$pays.'" LIMIT 1';
        if($data=$this->_getOneResult($sqlCheckVille)){
            $this->_region_id = $data['region_id'];
            return $data['id'];
        }else{
            return 0;
        }
    }
    /**
     * renvoi l'une ville existante ou la créé
     * @param string $nom
     * @param int $cp
     * @param string $pays
     * @return int
     */
    private function _insertVille($nom,$cp,$pays='france'){
        $idcheck = $this->_checkVille($nom,$cp,$pays);
        if($idcheck>0){
            return $idcheck;
        }elseif($nom!=''&&$cp!=''){
            // associer la région
            $dep = substr($cp,0,2);
            $sqlRegion = 'SELECT id FROM '.modele_region::getTable().' WHERE ';
            $sqlRegion .= 'departements="'.$dep.'" OR ';
            $sqlRegion .= 'departements LIKE "'.$dep.'-%" OR ';
            $sqlRegion .= 'departements LIKE "%-'.$dep.'-%" OR ';
            $sqlRegion .= 'departements LIKE "%-'.$dep.'" LIMIT 1';
            $resultRegion = bdd_sql::doSql($sqlRegion,true);
            if($resultRegion['count']==1){
                $region_id = $resultRegion['results'][0]['id'];
                $this->_region_id = $region_id;
            }else{
                $region_id = 0;
            }
            
            $sqlCreateVille = 'INSERT INTO '.PWE::getPrefixBdd().'ville (nom,cp,region_id,pays) VALUES ("'.$nom.'","'.$cp.'",'.$region_id.',"'.$pays.'")';
            bdd_sql::doSql($sqlCreateVille,false);
            return bdd_sql::getLastInsertId();
        }else{
            return 0;
        }
    }
    public function save(){
        $this->_ville_id = $this->_insertVille($this->_ville, $this->getCp(),$this->getPays(true));
        if($this->_ville_id>0){
            $sqlQueryAdresse = 'INSERT INTO '.self::getTable().' (adresse1,adresse2,ville_id,lat,lng,url_google) VALUES (';
            $sqlQueryAdresse .= '"'.$this->getAdresse1(true).'",';
            $sqlQueryAdresse .= '"'.$this->getAdresse2(true).'", ';
            $sqlQueryAdresse .= $this->getVilleId().', ';
            $sqlQueryAdresse .= '"'.$this->getLat().'", ';
            $sqlQueryAdresse .= '"'.$this->getLng().'", ';
            $sqlQueryAdresse .= '"'.$this->getUrlGoogle().'") ';
            bdd_sql::doSql($sqlQueryAdresse,false);
            $this->_id = bdd_sql::getLastInsertId();
            
            return array('success'=>true,'datas'=>$this->getDatas());
        }else{
            return array('success'=>false,'datas'=>array());
        }
    }
    public function update(){
        $this->_ville_id = $this->_insertVille($this->_ville, $this->getCp(),$this->getPays(true));
        
        if($this->_ville_id>0){
            $sqlQueryAdresse = 'UPDATE '.self::getTable().' SET ';
            $sqlQueryAdresse .= 'adresse1="'.$this->getAdresse1(true).'",';
            $sqlQueryAdresse .= 'adresse2="'.$this->getAdresse2(true).'", ';
            $sqlQueryAdresse .= 'lat="'.$this->getLat().'", ';
            $sqlQueryAdresse .= 'lng="'.$this->getLng().'", ';
            $sqlQueryAdresse .= 'url_google="'.$this->getUrlGoogle().'", ';
            $sqlQueryAdresse .= 'ville_id='.$this->getVilleId().' ';
            $sqlQueryAdresse .= 'WHERE id='.$this->_id.' LIMIT 1';
            bdd_sql::doSql($sqlQueryAdresse,false);
            
            return array('success'=>true,'datas'=>$this->getDatas());
        }else{
            return array('success'=>false,'datas'=>array());
        }
    }
    public function delete() {
        $sqlDelete = 'DELETE FROM '.self::getTable().' WHERE id='.$this->_id;
        bdd_sql::doSql($sqlDelete,false);

        return array('success'=>true,'datas'=>array());
    }
    
    /* function static */
    /**
     * 
     * @return string
     */
    public static function getTable(){
        return PWE::getPrefixBdd().self::$_table;
    }
    
    public static function getListeRegion(){
        $sqlRegion = 'SELECT * FROM '.modele_region::getTable();
        $results = bdd_sql::doSql($sqlRegion,true);
        
        return $results['results'];
    }
}
?>